import React, { useEffect, useState, useRef } from 'react';
import { Spin, Tooltip, Input } from 'antd';
import { LeftOutlined, RightOutlined, ZoomInOutlined, ZoomOutOutlined } from '@ant-design/icons';
 
import { Document, Page, pdfjs } from "react-pdf";
import 'react-pdf/dist/esm/Page/AnnotationLayer.css';
import 'react-pdf/dist/esm/Page/TextLayer.css';
import styles from "./PdfViewer.module.scss";
import { play } from '../../../api/course';
import { course as Course } from "../../../api/index";
pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.mjs`;
 
interface PropInterface {
    filePath:any,
    record: any,
    hour: any,
    isSave: boolean,
    children?:never[],
}

export const PdfViewer : React.FC<PropInterface> = ({
  filePath,
  record,
  hour,
  isSave,
})  => {
 
  const [pageCurrent, setPageCurrent] = useState(1);
  const pageCurrentRef = useRef(pageCurrent);
 
  const [pageTotal, setPageTotal] = useState(1);
  const pageTotalRef = useRef(pageTotal);
 
  const [pageWidth, setPageWidth] = useState(960);
  const pageWidthRef = useRef(pageWidth);    

  const [playingTime, setPlayingTime] = useState(0);
  const [playDuration, setPlayDuration] = useState(0);
  const myRef = useRef(0);
  const playRef = useRef(0);
  const watchRef = useRef(0);
  const totalRef = useRef(0);
  const timeRef = useRef(0);
 
  useEffect(()=>{  
    if(isSave) {
      setPageCurrent(record ?record.current_page:1);
      pageCurrentRef.current= record ?record.current_page:1;
    } else {
      setPageCurrent(1);
      pageCurrentRef.current= 1;
    }   
    totalRef.current = hour?.duration || 0; // 本课时应完成总时长
    myRef.current = record?.finished_duration || 0; //本课时已看多少时长 
    return () => {
      clearInterval(timeRef.current);// 清除定时器
      if(isSave) {
        // 更新学员观看时长
        if((watchRef.current + myRef.current) <= totalRef.current && !(watchRef.current == 0 && watchRef.current == 0)) {
          Course.record(
            Number(hour.course_id),
            Number(hour.id),
            (watchRef.current+myRef.current),
            Number(pageCurrentRef.current)
          ).then((res: any) => {
            Course.playPing(Number(hour.course_id), Number(hour.id)).then(
              (res: any) => {}
            );
          });
        }
      }
    }
  },[filePath, hour, record]) 

  useEffect (() => {
    watchRef.current = playDuration; //已播放多少时长
  }, [playDuration])

  useEffect (() => {
     playRef.current = playingTime; //上次保存的时间起点
  }, [playingTime])

  const createTimer = () => {
    timeRef.current = setInterval(() => {
      setPlayDuration(watchRef.current+1) 
      // 十秒钟或者完成时更新一次学习时长记录
      if((watchRef.current - playRef.current >= 10 && (watchRef.current + myRef.current) < totalRef.current)
         || (watchRef.current + myRef.current) === totalRef.current) {
        setPlayingTime(watchRef.current);
        Course.record(
          Number(hour.course_id),
          Number(hour.id),
          (watchRef.current+myRef.current),
          Number(pageCurrentRef.current)
        ).then((res: any) => {
          Course.playPing(Number(hour.course_id), Number(hour.id)).then(
            (res: any) => {}
          );
        });
      }
    }, 1000);
  }
 
  const prevPage = () => {
    if (pageCurrentRef.current == 1) { return; }
    setPageCurrent(pageCurrentRef.current - 1);
    pageCurrentRef.current= pageCurrentRef.current - 1;
  };
 
  const nextPage = () => {
    if (pageCurrentRef.current == pageTotalRef.current) {
      return;
    }
     
    setPageCurrent(pageCurrentRef.current + 1);
    pageCurrentRef.current= pageCurrentRef.current + 1;
  };
 
  const pageNumChange = (e:any) => {
    let value = Number(e.target.value);
    let value2 = 1;
 
    if(value<=0){
        value2 = 1;
    } else if(value >= pageTotalRef.current){
        value2 = pageTotalRef.current;
    } else {
        value2 = value;
    }
   
    setPageCurrent(value);
    pageCurrentRef.current= value;
  };
 
  const toPage = (e:any) => {
    console.log('toPage====',e)
    let value = Number(e.target.value);
    let value2 = value;
 
    if(value<=0){
        value2 = 1;
    } else if(value >= pageTotalRef.current){
        value2 = pageTotalRef.current;
    } else {
        value2 = value;
    }
    setPageCurrent(value2);
    pageCurrentRef.current= value2;
  };
 
  const pageZoomOut = () => {
    if (pageWidthRef.current <= 960) {
      return
    }
    const pageWidth = pageWidthRef.current * 0.8;   
    setPageWidth(pageWidth);   
    pageWidthRef.current = pageWidth;
  };
 
  const pageZoomIn = () => {
    const pageWidth = pageWidthRef.current * 1.2
    setPageWidth(pageWidth);   
    pageWidthRef.current = pageWidth;
  };
 
  const onDocumentLoadSuccess = (args:any) => {
    setPageTotal(args.numPages);
    pageTotalRef.current = args.numPages;
    if(isSave) {
      // 开始计时
      setPlayDuration(0);
      createTimer();
    }
  };
 
  return (
    <div className={styles["pdfViewer-wrapper"]}>
      {filePath?(<>
        <div className={styles["pageContainer"]}>
          <Document file={filePath} onLoadSuccess={ onDocumentLoadSuccess }  loading={<Spin size="large" />} >
            <Page pageNumber={pageCurrent} width={pageWidth} loading={<Spin size="large" />}  />
          </Document>
        </div>
 
        <div className={styles["pageTool"]}>
          <Tooltip title={pageCurrent == 1 ? "已是第一页" : "上一页"}>
            <LeftOutlined onClick={prevPage} />
          </Tooltip>
          <Input value={pageCurrent} onChange={ pageNumChange } onPressEnter={ toPage } type="number" /> / {pageTotal}
          <Tooltip title={pageCurrent == pageTotal ? "已是最后一页" : "下一页"}>
            <RightOutlined onClick={ nextPage } />
          </Tooltip>
          <Tooltip title="放大">
            <ZoomInOutlined onClick={ pageZoomIn } />
          </Tooltip>
          <Tooltip title="缩小">
            <ZoomOutOutlined onClick={ pageZoomOut } />
          </Tooltip>      
        </div>
      </>):(<div className={styles["empty-wrapper"]}>未生成报告文件！</div>)}
    </div>
  ); 
};